package com.ysc.databaseconfig;

import com.baomidou.mybatisplus.generator.config.IDbQuery;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.querys.OracleQuery;
import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @className: com.ysc.databaseconfig
 * @description: 获取配置文件数据
 * @author: YaoSiCheng
 * @date: 2024-07-12 15:41
 **/
public class DataSourcesConfig {

    private static final String FILE_NAME = "src/main/resources/application.yml";
    private static final String ORACLE = "oracle";
    private static final String MYSQL = "mysql";
    private static final String POSTGRESQL = "postgresql";

    /**
     * @title: getDataSource
     * @description: 获取数据库配置
     * @date: 2024-07-15 14:57:09
     * @author: YaoSiCheng
     * @param: name
     * @return: String
     */
    public static String getDataSource(String name) {
        try (InputStream in = Files.newInputStream(Paths.get(FILE_NAME))) {
            Yaml yaml = new Yaml();
            Map<String, Object> data = yaml.load(in);
            // 获取环境
            String active = (String) data.get("spring.profiles.active");
            if (StringUtils.isBlank(active)) {
                active = ORACLE;
            }
            return (String) data.get(active + "." + name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @title: getActive
     * @description: 获取环境变量
     * @date: 2024-07-15 14:58:22
     * @author: YaoSiCheng
     * @param:
     * @return: String
     */
    public static String getActive() {
        try (InputStream in = Files.newInputStream(Paths.get(FILE_NAME))) {
            Yaml yaml = new Yaml();
            Map<String, Object> data = yaml.load(in);
            // 获取环境
            return (String) data.get("spring.profiles.active");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @title: getDbQuery
     * @description: 获取查询方式
     * @date: 2024-07-15 15:00:47
     * @author: YaoSiCheng
     * @param:
     * @return: IDbQuery
     */
    public static IDbQuery getDbQuery() {
        if (ORACLE.equals(getActive())) {
            return new OracleQuery();
        } else if (MYSQL.equals(getActive())) {
            return new MySqlQuery();
        } else if (POSTGRESQL.equals(getActive())) {
            return new PostgreSqlQuery();
        }
        return null;
    }
}
